<?php
namespace control;
/*
*辅助成本核算类
*/

class costCountStatisticsClass extends adIndexClass
{
    private const page = 'costCountStatistics';
    private const title = '辅助成本核算';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'month'          => [
                        'name'  => "月份",
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'code'  => [
                        'name'  => '产品编码',
                        'width' => 200,
                    ],
                    'name'         => [
                        'name'  => '产品名称',
                        'width' => 200,
                    ],
                    'model'          => [
                        'name'  => '规格型号',
                        'width' => 200,
                    ],
                    'unit'          => [
                        'name'  => '单位',
                        'width' => 100,
                    ],
                    'num'          => [
                        'name'  => '实际产量',
                        'width' => 120,
                    ],
                    'materialFee'          => [
                        'name'  => '材料耗用(' . static::$unit . ')',
                        'width' => 120,
                    ],
                    'peopleFee'          => [
                        'name'  => '工人计件(' . static::$unit . ')',
                        'width' => 120,
                    ],
                    'disFee'          => [
                        'name'  => '分摊费用(' . static::$unit . ')',
                        'width' => 120,
                    ],
                    'costFee'          => [
                        'name'  => '成本合计(' . static::$unit . ')',
                        'width' => 120,
                    ],
                    'costPrice'          => [
                        'name'  => '成本单价(' . static::$unit . ')',
                        'width' => 120,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "产品编码" => text(array("name" => "code")),
                    "产品名称"   => text(array("name" => "materialName")),
                    "月份" => text(array("name" => "createTime", 'laydate' => ['type' => 'month', 'range' => '~'])),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, 'import')) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','importFrame',{cla:'".self::page."'})\">导入</span>";
        }
        if ($this->power(self::page, "export")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."'})\">导出</span>";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            'c.name' => $this->post('materialName'),
            'c.code' => $this->post('code'),
        );
        //全等查询数组
        $equal = array(
            "a.coid" => self::$coid,
            "a.type" => '生产入库',
        );
        $in = array(
            "a.state" => ['已入库', '已复核'],
        );
        $and = '';
        if ($this->post('createTime')) {
            $and .= self::timeComparison($this->post('createTime'), 'month', field: 'a.recordDate');
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'month desc,mx.materialId',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal, 'in' => $in)) . $and . " group by date_format(recordDate,'%Y-%m'),mx.materialId";
        $page = $this->page(array(
            "table" => "inventory_changes as a join inventory_changes_detail as mx on a.id = mx.orderId join material as c on c.id = mx.materialId ",
            "where" => $where,
            'field' => "date_format(a.recordDate,'%Y-%m') as month,mx.materialId,ifnull(sum(any_value(mx.num)),0) as num",
            "order" => $orderBy['orderBy']
        ));
        static::rSet(self::$stid . self::page . 'Sql', $page['fullSql']);
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array();
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $mateial = query('material', "id = '$array[materialId]'");
            $cost_count_statistics = query(
                'cost_count_statistics',
                "month = '$array[month]' and coid = '" . self::$coid . "' and materialId = '$array[materialId]'"
            );
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'code':
                    case 'name':
                    case 'model':
                    case 'unit':
                        $row[] = html_entity_decode($mateial[$key]);
                        break;
                    case 'num':
                        $num = $this->inFee($array['month'], $array['materialId']);
                        $row[] = self::lostZero($num, 'numPrecision');
                        break;
                    case 'materialFee':
                    case 'peopleFee':
                    case 'disFee':
                    case 'costFee':
                        $row[] = self::lostZero($cost_count_statistics[$key]);
                        break;
                    case 'costPrice':
                        $row[] = self::lostZero($cost_count_statistics['costPrice'], 'pricePrecision');
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }


    /**
     * 分摊费用
     */
    public function inFee($month, $materialId): float|int
    {
        $totalNum = 0;//实际产量
        $inventoryAll = find(array(
            'table' =>'inventory_changes_detail as a join inventory_changes as b on a.orderId = b.id',
            'field'=>"a.*",
            'where' => "date_format(b.recordDate,'%Y-%m') = '$month' and a.coid = '".self::$coid."' and b.type = '生产入库' and a.materialId = '$materialId' and b.state in ('已入库','已复核') order by a.list"
        ));
        foreach ($inventoryAll['array'] as $inventoryDetail) {
            $material = query('material', "id = '$inventoryDetail[materialId]'");
            $num = machiningOrderClass::material_num_change($inventoryDetail['materialId'], $inventoryDetail['unit'], $material['unit'], $inventoryDetail['num']);
            $totalNum += $num;
        }
        return $totalNum;
    }


    /**
     * 下载模板
     */
    public function downloadModel()
    {
        $templateId = $this->get('templateId');
        if (!$this->power(self::page, 'import')) {
            $_SESSION['warn'] = '你还没有导入的权限';
        }   else {
            $exampleData = [];
            $sql = static::rGet(self::$stid . self::page . 'Sql');
            $result = sqlFind($sql);
            if (is_array($result)) {
                foreach ($result as $array) {
                    $num = $this->inFee($array['month'], $array['materialId']);
                    $mateial = query('material', "id = '$array[materialId]'");
                    $exampleData[] = array(
                        $array['month'],
                        $mateial['code'],
                        html_entity_decode($mateial['name']),
                        $mateial['model'],
                        $mateial['unit'],
                        self::lostZero($num, 'numPrecision'),
                        '',
                        '',
                        '',
                        ''
                    );
                }
            }
            $excel    = $this->excelHead();
            $fileName = self::title.'导入模板-'.importTemplateClass::getName($templateId).'.xlsx';
            $filePath = $excel->fileName($fileName, 'sheet1');
            $format = new \Vtiful\Kernel\Format($filePath->getHandle());
            $templateField = importTemplateClass::templateField(self::page, 'importFieldInit', id:$templateId);
            $index         = 0;
            foreach ($templateField as $k => $array) {
                if ($array['display']){
                    $backgroundStyle=null;
                    if (importTemplateClass::getIsMustValue($this->importFieldInit(), $array['columnName'])){
                        //必填项判断
                        $backgroundStyle  = $format->background(
                            0xFFC04B
                        )->toResource();
                    }
                    $filePath->insertText(0, $index, $array['aliasName'],'',$backgroundStyle);
                    foreach ($exampleData as $y=>$example){
                        $filePath->insertText($y+1, $index, $example[$k]??'');
                    }
                    $index++;
                }
            }
            $text = $this->control['name'] . "下载了" . self::title . "导入模板";
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOutPut($filePath,$fileName);
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }

    /*数据导入*/
    public function importData()
    {
        $templateId = $this->post('templateId');
        if (!$this->power(self::page, 'import')) {
            $json['warn'] = '你还没有导入的权限';
        } else {
             $fomatArray = [];//导入数据格式同一为TYPE_STRING
            foreach ($this->importFieldInit() as $value){
                $fomatArray[] = \Vtiful\Kernel\Excel::TYPE_STRING;
            }
            $data = $this->importHead(format: $fomatArray);
            $x = 0;
            $text = '';
            $headArray = [];
            $row_list=0;
            foreach ($data as $i => $row) {
                $row_list++;
                if ($i==0){
                    $templateField = importTemplateClass::templateField(self::page, 'importFieldInit', id:$templateId);
                    $headArray = importTemplateClass::combinHead($templateField,$row);
                }
                if ($i > 0) {
                    $rowData = formSubArray($row);
                    //只接收模板中选中的字段的值
                    $cell = [];
                    foreach ($headArray as $index=>$headName){
                        $cell[$headName] = $rowData[$index]??'';
                    }
                    //初始化未被模板需要的字段的值
                    foreach ($this->importFieldInit() as $value){
                        $cell[$value['columnName']] = $cell[$value['columnName']]??'';
                    }
                    $material = query('material', "coid = '" . self::$coid . "' and model = '$cell[规格型号]' and name = '$cell[产品名称]'");
                    $cell['实际产量'] = $cell['实际产量'] ?: 0;
                    $cell['成本合计'] = $cell['成本合计'] ?: 0;
                    $field = [
                        'month' => $cell[0],
                        'sourceTable' => 'inventory_changes',
                        'sourceId' => '',
                        'materialId' => $material['id'],
                        'num' => $cell['实际产量'],
                        'unit' => $material['unit'],
                        'materialFee' => $cell['材料耗用'] ?: 0,
                        'peopleFee' => $cell['工人计件'] ?: 0,
                        'disFee' => $cell['分摊费用'] ?: 0,
                        'costFee' => $cell['成本合计'],
                        'costPrice' => self::formattingFigure($cell['实际产量'] > 0 ? $cell['成本合计'] / $cell['实际产量'] : 0, 'pricePrecision'),
                    ];
                    $annotation = [
                        'month' => '月份',
                        'materialId' => '产品编码',
                    ];
                    $rules = [
                        'month' => 'required',
                        'materialId' => 'required',
                    ];
                    $info = query('cost_count_statistics', "month = '$field[month]' and coid = '" . self::$coid . "' and materialId = '$field[materialId]'");
                    // 校验是否符合规则
                    $vt = new \verify();
                    $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
                    if ($result === false) {
                        $text .= "\n第【{$row_list}】行，" . $vt->getErrs()[0];
                    } elseif (round(($field['peopleFee'] + $field['materialFee'] + $field['disFee']), 2) != $field['costFee']) {
                        $text .= "\n第【{$row_list}】行，材料耗用+工人计件+分摊费用不等于成本合计";
                    } else {
                        if (empty($info['id'])) {
                            // 新增
                            $field = array_merge($field, [
                                'id' => suiji(),
                                'coid' => self::$coid,
                            ]);
                            $warn = static::insert([
                                "table" => 'cost_count_statistics',
                                "field" => $field,
                            ]);
                        } else {
                            $warn = static::update([
                                "table" => 'cost_count_statistics',
                                "field" => $field,
                                'where' => "id = '$info[id]'"
                            ]);
                        }
                        if (in_array($warn, ["新增成功", "更新成功"])) {
                            $x++;
                            //重新更新生产领料的单价
                            $all = find([
                                'table' => 'inventory_changes_detail as a join inventory_changes as b on a.orderId = b.id',
                                'field'=>"a.*",
                                'where' => "date_format(b.recordDate,'%Y-%m') = '$field[month]' and a.coid = '".self::$coid."' and b.type = '生产入库' and a.materialId = '$field[materialId]' and b.state in ('已入库','已复核') order by a.list"
                            ]);
                            foreach ($all['array'] as $val) {
                                $num = machiningOrderClass::material_num_change($val['materialId'], $material['unit'], $val['unit']);
                                if ($num > 0) {
                                    $price = self::formattingFigure($field['costPrice'] / $num, 'pricePrecision');
                                    static::update([
                                        'table' => 'inventory_changes_detail',
                                        'where' => "id = '$val[id]'",
                                        'field' => ['price' => $price, 'money' => self::formattingFigure($price * $val['num'])]
                                    ]);
                                }
                            }
                            inventoryDefaultClass::recordInventoryPrice($field['materialId'], $field['num'], $field['costPrice']);
                            $text .= "\n第【{$row_list}】行，导入成功";
                        } else {
                            $text .= "\n第【{$row_list}】行，编辑数据失败，" . $warn;
                        }
                    }
                }
            }
            $total = count($data)-1;
            $json['data'] = [
                'text'=>$text,
                'title'=>"您导入了{$total}条数据，成功{$x}条，失败".($total-$x)."条",
            ];
            $text = $this->control['name'] . '导入了文件：' . $_FILES['file']['name'] . '：' . $text;
            $this->logText(["type" => self::page, "text" => $text]);
            $json['warn'] = 2;
        }
        return json_encode($json,320);
    }

    /**
     * 导出
     */
    public function exportData()
    {
        $templateId = $this->get('templateId');
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        }  else {
            $data = [];
            /***********标题**********/
            $title =[];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']){
                    $title[] = $array['aliasName'];
                }
            }
            $sql = static::rGet(self::$stid . self::page . 'Sql');
            $result   = sqlFind($sql);
            //导出数据生成
            foreach ($result as $array){
                $column = [];
                $num = $this->inFee($array['month'], $array['materialId']);
                $mateial = query('material', "id = '$array[materialId]'");
                $cost_count_statistics = query(
                    'cost_count_statistics',
                    "month = '$array[month]' and coid = '" . self::$coid . "' and materialId = '$array[materialId]'"
                );
                foreach ($tempFieldAll as $templateField){
                    if ($templateField['display']){
                        $column[] = match ($templateField['columnName']){
                            '月份'=>$array['month'],
                            '产品编码'=>$mateial['code'],
                            '产品名称'=>html_entity_decode($mateial['name']),
                            '规格型号'=>$mateial['model'],
                            '单位'=>$mateial['unit'],
                            '实际产量'=>self::lostZero($num, 'numPrecision'),
                            '材料耗用'=> $cost_count_statistics['materialFee'],
                            '工人计件'=>$cost_count_statistics['peopleFee'],
                            '分摊费用'=>$cost_count_statistics['disFee'],
                            '成本合计'=> $cost_count_statistics['costFee'],
                            '成本单价'=> self::lostZero($cost_count_statistics['costPrice'], 'pricePrecision'),
                            default=>'',
                        };
                    }
                }
                $data[] = $column;
            }
            $text = $this->control['name'] . "导出了" . self::title;
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, self::title . ".xlsx");
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));

    }

    /**
     * 导入模板字段初始化
     * @return array[]
     */
    public function importFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'月份',
                    'aliasName'=>'月份',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'产品名称',
                    'aliasName'=>'产品名称',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'规格型号',
                    'aliasName'=>'规格型号',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'单位',
                    'aliasName'=>'单位',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'实际产量',
                    'aliasName'=>'实际产量',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'材料耗用',
                    'aliasName'=>'材料耗用',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'工人计件',
                    'aliasName'=>'工人计件',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'分摊费用',
                    'aliasName'=>'分摊费用',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'成本合计',
                    'aliasName'=>'成本合计',

                    'isMust'=>true,
                ],
            ]
        };
    }

    /**
     * 导出模板字段初始化
     * @return array[]
     */
    public function exportFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'月份',
                    'aliasName'=>'月份',
                ],
                [
                    'columnName'=>'产品编码',
                    'aliasName'=>'产品编码',
                ],
                [
                    'columnName'=>'产品名称',
                    'aliasName'=>'产品名称',
                ],
                [
                    'columnName'=>'规格型号',
                    'aliasName'=>'规格型号',
                ],
                [
                    'columnName'=>'单位',
                    'aliasName'=>'单位',
                ],
                [
                    'columnName'=>'实际产量',
                    'aliasName'=>'实际产量',
                ],
                [
                    'columnName'=>'材料耗用',
                    'aliasName'=>'材料耗用(元)',
                ],
                [
                    'columnName'=>'工人计件',
                    'aliasName'=>'工人计件(元)',
                ],
                [
                    'columnName'=>'分摊费用',
                    'aliasName'=>'分摊费用(元)',
                ],
                [
                    'columnName'=>'成本合计',
                    'aliasName'=>'成本合计(元)',
                ],
                [
                    'columnName'=>'成本单价',
                    'aliasName'=>'成本单价(元)',
                ],
            ]
        };
    }
}

